package com.ruoyi.chy.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;

@RestController
public class GeocoderController {

    @Value("${tencent.map.key}")
    private String tencentMapKey;

    // 代理接口：/api/geocoder
    @GetMapping("/api/geocoder")
    public Mono<Object> geocoder(
            @RequestParam("latitude") String latitudeStr,
            @RequestParam("longitude") String longitudeStr
    ) {
        Double latitude = Double.parseDouble(latitudeStr);
        Double longitude = Double.parseDouble(longitudeStr);
        // 构建腾讯地图API请求URL
        String baseUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + latitude + "," + longitude + "&key=" + tencentMapKey + "&get_poi=0";

        // 使用WebClient调用腾讯API
        return WebClient.create()
                .get()
                .uri(baseUrl)
                .retrieve()
                .bodyToMono(Object.class)  // 直接返回腾讯API的响应结果
                .onErrorResume(error ->
                        Mono.just(new HashMap<String, Object>() {{  // 替换Map.of()为HashMap
                            put("status", 1);
                            put("message", "调用腾讯API失败: " + error.getMessage());
                        }})
                );
    }
}